﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using FarseerPhysics.Dynamics;
using Microsoft.Xna.Framework;
using SFML.Graphics;
using Theta.Components;
using Theta.Entities;

namespace Theta.Physics
{
    public class PhysicsManager
    {
        World _world;
        Dictionary<Drawable, Body> _drawableBodies;

        public Body this[Drawable key]
        {
            get
            {
                foreach(KeyValuePair<Drawable, Body> drawableBody in _drawableBodies)
                {
                    if (drawableBody.Key == key)
                        return drawableBody.Value;
                }
                return null;
            }
        }

        public Vector2 Gravity
        {
            get { return _world.Gravity; }
            set { _world.Gravity = value; }
        }

        public World World
        {
            get { return _world; }
        }

        [DefaultValue(typeof(float), "1f / 60f")]
        public float StepRatio { get; set; }

        public PhysicsManager()
        {
            _world = new World(new Vector2(0, 5));
            _drawableBodies = new Dictionary<Drawable, Body>();

            StepRatio = 1f / 60f;
        }

        public void AttachBody(Drawable drawable, Body body)
        {
            _drawableBodies.Add(drawable, body);
        }

        public void Update(TimeSpan elapsedTime)
        {
            _world.Step(Math.Min((float)elapsedTime.TotalSeconds, (1f / 60f)));

            foreach(KeyValuePair<Drawable, Body> pair in _drawableBodies)
            {
                pair.Key.Position = Converter.ToPixels(Converter.ToVector2f(pair.Value.Position));
                pair.Key.Rotation = pair.Value.Rotation;
            }
        }
    }
}